package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //用户登录
    public Map login(Map map) {
        //获取请求参数
        String uuid = (String) map.get("uuid");
        String verificationCode = (String) map.get("verificationCode");
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        //判断用户名或者密码是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new BusinessException("用户名和密码不能为空");
        }
        //判断验证码是否为空
        if (StringUtils.isBlank(verificationCode)){
            throw new BusinessException("验证码不能为空");
        }
        //判断验证码是否正确
        String radisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (!verificationCode.equals(radisCode)){
            throw new BusinessException("验证码错误");
        }
        //查询用户信息
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername, username));
        //判断信息是否正确
        if (!admin.getPassword().equals(SecureUtil.md5(password))){
            throw new BusinessException("用户名或密码错误");
        }
        //生成token>
        Map params = new HashMap<>();
        params.put("id",admin.getId());
        params.put("username",username);
        String token = JwtUtils.getToken(params);
        //返回结果
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    //获取管理员信息
    public AdminVo profile(Long userId) {
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getId, userId));
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }
}
